<?php
namespace app\api\model;
use app\common\model\Goods as GoodsModel;

/**
 * 菜品模型
 */
class Goods extends GoodsModel
{
    /**
     * 隐藏字段
     */
    protected $hidden = [
        'spec_rel',
        'delivery',
        'sales_initial',
        'sales_actual',
        'is_delete',
        'wxapp_id',
        'create_time',
        'update_time'
    ];
	
	/**
     * 按照分类获取上架的所有商品
	 *$food_mode 1堂食 2打包自取 3外卖
     */
	public function getGoodsList($shop_id,$category,$user,$food_mode)
	{
		//获取当前购物车商品
		$cart = new Cart($user['user_id'],$shop_id);
		$cart_data = $cart->getCart();
		$cartlist = $cart->getList($user,$food_mode);
		$list=array();
		for($i=0;$i<sizeof($category);$i++){
			$deail = $this->with(['image.file', 'spec', 'spec_rel.spec'])
						->where([
							'goods_status' => 10, 
							'is_delete' => 0,
							'category_id' => $category[$i]['category_id'],
							'shop_id' => $shop_id
						])
						->order(['goods_sort', 'goods_id' => 'desc'])
						->select();
			$goods = [];
			if($food_mode == 3){
				//筛选外卖产品
				for($n=0;$n<sizeof($deail);$n++){
					if($deail[$n]['spec'][0]['out_price']>0){
							array_push($goods,$deail[$n]);
					}
				}
			}
			if($food_mode < 3){
				//筛选堂食产品
				for($n=0;$n<sizeof($deail);$n++){
					if($deail[$n]['spec'][0]['goods_price']>0){
							array_push($goods,$deail[$n]);
					}
				}
			}
			// 规格信息
			for($n=0;$n<sizeof($goods);$n++){
				$goods[$n]['total_num'] = 0;//购物车数量
				if($goods[$n]['spec_type'] == 20){
					$goods[$n]['specData'] = $this->getManySpecData($goods[$n]['spec_rel'], $goods[$n]['spec']);
					for($s=0;$s<sizeof($goods[$n]['spec']);$s++){
						$goods[$n]['spec'][$s]['sell_num']=0;
						if(isset($cart_data[$goods[$n]['goods_id'].'_'.$goods[$n]['spec'][$s]['spec_sku_id']])){
							$goods[$n]['total_num'] = $goods[$n]['total_num'] + $cart_data[$goods[$n]['goods_id'].'_'.$goods[$n]['spec'][$s]['spec_sku_id']]['goods_num'];	
							$goods[$n]['spec'][$s]['sell_num'] = $cart_data[$goods[$n]['goods_id'].'_'.$goods[$n]['spec'][$s]['spec_sku_id']]['goods_num'];
						}
					}
				}else{
					if(isset($cart_data[$goods[$n]['goods_id'].'_'])){
						$goods[$n]['total_num'] = $cart_data[$goods[$n]['goods_id'].'_']['goods_num'];	
					}
					$goods[$n]['specData'] = null;
				}
			}
			$list[$category[$i]['category_id']] = $goods;
		}
		return compact('list','cartlist');
	}

    /**
     * 商品详情：HTML实体转换回普通字符
     */
    public function getContentAttr($value)
    {
       return htmlspecialchars_decode($value);
    }

    /**
     * 根据商品id集获取商品列表 (购物车列表用)
     */
    public function getListByIds($goodsIds) {
        return $this->with(['category', 'image.file', 'spec', 'spec_rel.spec'])
            ->where('goods_id', 'in', $goodsIds)->select();
    }

}
